//
//  BroadcastPack.m
//  YSSmartHome
//
//  Created by Yahaong on 16/8/18.
//  Copyright © 2016年 yahaong. All rights reserved.
//

#import "BroadcastPack.h"
#import <XAISDK/XAIConvertorHelper.h>

static int const BROADCASTFIXEDALL = 14;
@implementation BroadcastPack
+ (BroadcastPack*) format:(void*)bytes length:(int)length
{
    if (bytes == NULL)
    {
        return nil;
    }
    if (length < BROADCASTFIXEDALL)
    {
        NSLog(@"format 长度不对");
        return nil;
    }
    BroadcastPack *broadcastPack  = [[BroadcastPack alloc]init];
    int index = 0;
    broadcastPack.flag = ((uint8_t*)bytes)[index];
    index += 1;
    uint32_t apsn = [XAIConvertorHelper bytesToInt:bytes offset:index];
    broadcastPack.apsn = CFSwapInt32(apsn);
    index += 4;
    
    uint64_t luid = [XAIConvertorHelper bytesToLong:bytes offset:index];
    broadcastPack.luid =  CFSwapInt64(luid);
    index += 8;
    
    broadcastPack.length = ((uint8_t*)bytes)[index];
    index += 1;
    broadcastPack.name = [[NSString alloc]initWithBytes:bytes + index length:broadcastPack.length encoding:NSUTF8StringEncoding];
    return broadcastPack;
}
- (NSData *)toData
{
    NSMutableData* toData  = [NSMutableData data];
    uint8_t flag = self.flag;
    [toData appendBytes:&flag length:sizeof(flag)];
    
    uint32_t apsn = CFSwapInt32(self.apsn);
    [toData appendBytes:&apsn length:sizeof(apsn)];
    
    uint64_t luid = CFSwapInt64(self.luid);
    [toData appendBytes:&luid length:sizeof(luid)];

    NSString* name = [NSString stringWithFormat:@"%@\0",self.name];
    NSData* nameData = [name dataUsingEncoding:NSUTF8StringEncoding];
    uint8_t length = nameData.length;
    [toData appendBytes:&length length:sizeof(length)];
    [toData appendData:nameData];
    return toData;
}
@end
